<template>
  <view class="vocab-container">
    <view class="vocab-header">
      <text class="title">单词学习</text>
    </view>
    
    <view class="vocab-tabs">
      <view class="tab-item" :class="{ active: activeTab === 'learn' }" @click="switchTab('learn')">学习</view>
      <view class="tab-item" :class="{ active: activeTab === 'review' }" @click="switchTab('review')">复习</view>
      <!-- <view class="tab-item" :class="{ active: activeTab === 'collect' }" @click="switchTab('collect')">收藏</view> -->
    </view>
    
    <view class="vocab-content">
      <!-- 学习标签页 -->
      <view class="learn-tab" v-if="activeTab === 'learn'">
        <view class="word-list" v-if="libraries.length > 0">
          <view class="word-item" v-for="(word, index) in libraries" :key="word.id">
            <view class="word-index">{{ index + 1 }}</view>
            <view class="word-info">
              <text class="word-text">{{ word.libraryName }}</text>
              <text class="word-phonetic">学习情况：{{ word.studiedWords }}/{{ word.totalWords }}</text>
              <!-- 学习数量选择区域 -->
              <view class="study-config">
                <text class="config-label">数量:</text>
                <view class="quantity-selector">
                  <text 
                    class="quantity-btn" 
                    :class="{ disabled: learnCount <= 5 }"
                    @click="decreaseStudyCount()"
                  >-</text>
                  <text class="quantity-number">{{ learnCount }}</text>
                  <text 
                    class="quantity-btn" 
                    :class="{ disabled: learnCount >= 50 }"
                    @click="increaseStudyCount()"
                  >+</text>
                </view>
                <text class="quantity-unit">个/天</text>
              </view>
            </view>
            
            <!-- 开始学习按钮 -->
            <view class="word-action">
              <button 
                class="start-btn" 
                :class="{ 'continue-btn': word.studiedWords > 0 }"
                @click="goToLearnPage(word)"
              >
                {{ word.studiedWords > 0 ? '继续学习' : '开始学习' }}
              </button>
            </view>
          </view>
        </view>
        <view class="empty-state" v-else>
          <image class="empty-icon" src="/static/icons/book.png" mode="aspectFit"></image>
          <text class="empty-text">暂无学习单词</text>
        </view>
      </view>
      
      <!-- 复习标签页 -->
      <view class="review-tab" v-else-if="activeTab === 'review'">
        <!-- 加载状态 -->
        <view class="loading" v-if="reviewLoading">
          <text>加载中...</text>
        </view>
        
        <!-- 空状态 -->
        <view class="empty" v-else-if="reviewWords.length === 0">
          <text class="empty-text">暂无需要复习的单词</text>
          <text class="empty-desc">继续保持学习进度</text>
        </view>
        
        <!-- 单词列表 -->
        <view v-else class="review-content">
          <scroll-view class="word-list" scroll-y>
            <view 
              v-for="(reviewWord, index) in reviewWords" 
              :key="reviewWord.id" 
              class="word-item"
            >
              <view class="word-main">
                <text class="word-text">{{ reviewWord.word }}</text>
              </view>
              <view class="word-meaning">
                <text class="meaning-text">  {{getWordMeaning(reviewWord) }}</text>
              </view>
            </view>
          </scroll-view>
          
          <!-- 开始复习按钮 -->
          <view class="start-review-btn-container">
            <button class="start-review-btn" @click="startReview">
              开始复习 ({{ reviewWords.length }})
            </button>
          </view>
        </view>
      </view>
      
      <!-- 收藏标签页 -->
      <!-- <view class="collect-tab" v-else-if="activeTab === 'collect'">
        <view class="word-list" v-if="collectedWords.length > 0">
          <view class="word-item" v-for="word in collectedWords" :key="word.id">
            <view class="word-info">
              <text class="word-text">{{ word.word }}</text>
              <text class="word-phonetic">{{ word.phonetic }}</text>
              <text class="word-meaning">{{ word.meaning }}</text>
            </view>
            <view class="word-action">
              <text class="collect-icon collected" @click="toggleCollect(word)">★</text>
            </view>
          </view>
        </view>
        <view class="empty-state" v-else>
          <text class="empty-text">暂无收藏单词</text>
        </view>
      </view> -->
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { api } from '@/api';
import { storageAsync } from '../../utils';

const activeTab = ref('learn');
const libraries = ref([]);
const learnCount = ref(20);
const collectedWords = ref([]);
const reviewStats = ref(null);
const reviewWords = ref([]);
const reviewLoading = ref(false);
var userInfo = null;

// 切换标签页
const switchTab = async (tab) => {
  activeTab.value = tab;
  await loadData();
};

// 加载数据
const loadData = async () => {
  try {
    if (activeTab.value === 'learn') {
      await loadLibraries();
    } else if (activeTab.value === 'review') {
      await loadReviewStats();
    } else if (activeTab.value === 'collect') {
      await loadCollectedWords();
    }
  } catch (error) {
    console.error('加载数据失败', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

// 加载学习单词
const loadLibraries = async () => {
	userInfo = await storageAsync.get("userInfo");
	const res = await api.vocab.getLibraryList(userInfo.id);
	libraries.value = res.data || [];
};

// 减少学习数量
const decreaseStudyCount = () => {
  if (learnCount.value > 5) {
    learnCount.value -= 5;
    saveStudyConfig();
  }
};

// 增加学习数量
const increaseStudyCount = () => {
  if (learnCount.value < 50) {
    learnCount.value += 5;  
    saveStudyConfig();
  }
};

// 保存学习配置到本地存储
const saveStudyConfig = async () => {
  try {
    await storageAsync.set('studyConfig', {
      learnCount: learnCount.value,
      updateTime: new Date().getTime()
    });
    console.log('学习数量已保存:', learnCount.value);
  } catch (error) {
    console.error('保存学习配置失败:', error);
  }
};

// 加载初始配置
const loadInitialConfig = async () => {
  try {
    const config = await storageAsync.get('studyConfig');
    if (config && config.learnCount) {
      learnCount.value = config.learnCount;
    }
  } catch (error) {
    console.error('加载学习配置失败:', error);
  }
};

// 加载收藏单词
const loadCollectedWords = async () => {
  const res = await api.vocab.getCollectedWords();
  collectedWords.value = res.data || [];
};

// 加载复习统计
const loadReviewStats = async () => {
	const res = await api.vocab.getReviewVocabs(20,userInfo.id);
	
	reviewWords.value = res.data.words||[];
	console.log('复习单词:', reviewWords.value);
	
};

// 获取单词释义
const getWordMeaning = (word) => {
	console.log('********单词:', word);
  if (word.translations && word.translations.length > 0) {
    return `${word.translations[0].pos} ${word.translations[0].cn}`;
  }
  
  return word.translation || '暂无释义';
};

// 切换收藏状态
const toggleCollect = async (word) => {
  try {
    if (word.isCollected) {
      await api.vocab.uncollectWord(word.id);
    } else {
      await api.vocab.collectWord(word.id);
    }
    word.isCollected = !word.isCollected;
    
    // 如果当前在收藏页，重新加载数据
    if (activeTab.value === 'collect') {
      await loadCollectedWords();
    }
  } catch (error) {
    console.error('收藏操作失败', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 学习单词 
const goToLearnPage = async (word) => {
  try {
    // 保存当前词书信息
    await storageAsync.set('currentLibrary', {
      id: word.id,
      studyCount: learnCount.value
    });
	await storageAsync.remove('reviewWords');
    
    uni.navigateTo({
      url: '/pages/vocab/learn'
    });
  } catch (error) {
    console.error('打开学习页面失败', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 开始复习
const startReview = async () => {
  try {
    if (reviewWords.length === 0) {
      uni.showToast({ title: '暂无需要复习的单词', icon: 'none' });
      return;
    }
	// 保存当前词书信息
	await storageAsync.set('reviewWords', reviewWords.value);
	await storageAsync.remove('currentLibrary');
    
    uni.navigateTo({
      url: '/pages/vocab/learn'
    });
  } catch (error) {
    console.error('获取复习单词失败', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
};

// 监听标签页变化
watch(activeTab, loadData);

// 初始加载
onMounted(async () => {
  await loadInitialConfig(); // 添加初始化配置加载
  await loadData();
});
</script>

<style scoped>
/* 样式保持不变 */
.vocab-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.vocab-header {
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.vocab-tabs {
  display: flex;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  padding: 20rpx 0;
  text-align: center;
  font-size: 32rpx;
  color: #666;
  border-bottom: 4rpx solid transparent;
}

.tab-item.active {
  color: #4A90E2;
  border-bottom-color: #4A90E2;
}

.vocab-content {
  flex: 1;
  overflow-y: auto;
}

.word-list {
  padding: 20rpx;
}

.word-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.word-index {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #4A90E2;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  margin-right: 20rpx;
}

.word-info {
  flex: 1;
}

.word-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.word-phonetic {
  font-size: 28rpx;
  color: #999;
  display: block;
  margin-bottom: 8rpx;
}

.word-meaning {
  font-size: 28rpx;
  color: #666;
  line-height: 40rpx;
}

.word-action {
  margin-left: 20rpx;
}

.collect-icon {
  font-size: 36rpx;
  color: #999;
}

.collect-icon.collected {
  color: #FFD700;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #999;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  opacity: 0.5;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
}

.review-tab {
  padding: 40rpx 20rpx;
}

.review-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 60rpx;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #4A90E2;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 28rpx;
  color: #666;
}

.review-btn {
  background-color: #4A90E2;
  color: #fff;
  border-radius: 50rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  width: 80%;
  margin: 0 auto;
}
  
.study-config {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 0;
}

.config-label {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
}

.quantity-btn {
  width: 32px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.quantity-btn:active {
  background-color: #e5e5e5;
}

.quantity-btn.disabled {
  color: #ccc;
  background-color: #f9f9f9;
}

.quantity-number {
  width: 40px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #333;
  background-color: white;
}

.quantity-unit {
  font-size: 14px;
  color: #666;
  margin-left: 8px;
}

.start-btn {
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  min-width: 80px;
  position: relative;
    z-index: 1;
    pointer-events: auto;
}

.start-btn:active {
  background-color: #acacac;
}

.continue-btn {
  background-color: #28A745; 
}

/* 复习页面样式 */
.review-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200rpx);
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  font-size: 32rpx;
  color: #666;
}

.empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  text-align: center;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #999;
}

.start-review-btn-container {
  position: fixed;
  bottom: 150rpx; /* 距离底部一些间距 */
  left: 20rpx;
  right: 20rpx;
  z-index: 1000;
}

.start-review-btn {
  width: 50%;
  height: 88rpx;
  line-height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.3); /* 添加阴影效果 */
}

.start-review-btn:active {
  opacity: 0.9;
  transform: translateY(2rpx); /* 点击时的反馈效果 */
}
</style>